package com.seal.yoyoshop.web;

import com.seal.yoyoshop.bin.Type;
import com.seal.yoyoshop.bin.User;
import com.seal.yoyoshop.service.TypeService;
import com.seal.yoyoshop.service.UserService;
import com.seal.yoyoshop.service.impl.TypeServiceImpl;
import com.seal.yoyoshop.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "ForgetServlet", value = "/index/forget")
public class ForgetServlet extends HttpServlet {

    private TypeService typeService = new TypeServiceImpl();
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        导航栏
        request.setAttribute("flag",6);
        List<Type> typeList = typeService.getTypeList();
        request.setAttribute("typeList",typeList);
//
        request.getRequestDispatcher("/index/forget.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //        导航栏
        request.setAttribute("flag",6);
        List<Type> typeList = typeService.getTypeList();
        request.setAttribute("typeList",typeList);
//      编码格式
        request.setCharacterEncoding("UTF-8");
//      获取前端数据
        String username =  request.getParameter("username");
        String phone = request.getParameter("phone");
//      查找用户
        User user = userService.getUserByUsername(username);
//        判断用户情况
        if(user == null){
            request.setAttribute("msg","用户不存在");
            request.getRequestDispatcher("/index/forget.jsp").forward(request,response);
        }else{
            if(phone.equals(user.getPhone())) {
//                执行更改密码操作
                String password = "123456";
                int flag = userService.updateUserPassword(username,password);
                System.out.println(flag);
                if(flag == 0){
                    request.setAttribute("msg","密码更改错误");
                    request.getRequestDispatcher("/index/forget.jsp").forward(request,response);
                }else {
                    request.setAttribute("msg","密码重置成功，新密码为123456");
//                    request.getRequestDispatcher("/index/forget.jsp").forward(request,response);
                    request.getRequestDispatcher("/index/login.jsp").forward(request, response);
                }
            }else {
                request.setAttribute("msg","手机号不一致");
                request.getRequestDispatcher("/index/forget.jsp").forward(request,response);
            }
        }


    }
}
